package com.da.auth.controller;


import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.da.auth.entity.constant.DailyAuthConstant;
import com.da.auth.entity.dto.UserInfoDTO;
import com.da.auth.entity.vo.UserInfoVO;
import com.da.auth.redis.RedisCache;
import com.da.auth.security.jwt.BaseContext;
import com.da.auth.security.service.UserInfoService;
import com.da.common.utils.DailyAimResult;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @Author: hyacinth
 * @CreateTime: 2025-02-10
 * @Version: 1.0
 */
@CrossOrigin // 允许跨域
@RestController
@RequestMapping("/dl")
@Tag(name = "用户管理接口")
@Slf4j
@RequiredArgsConstructor
public class LoginController {

    private final UserInfoService userInfoService;

    private final RedisCache redisCache;

    /**
     * 用户登录
     * @param userInfoDTO 用户登录信息
     * @return  统一返回结果
     */
    @PostMapping("/login")
    @Operation(summary = "员工登录")
    public DailyAimResult<UserInfoVO> login(@Validated @RequestBody UserInfoDTO userInfoDTO) {
        log.info("员工：{}，登录成功", userInfoDTO.getUsername());
        UserInfoVO empLoginVO = userInfoService.login(userInfoDTO);
        return DailyAimResult.success(empLoginVO);
    }

    /**
     * 用户退出登录
     * @return  统一返回结果
     */
    @PostMapping("/logout")
    @Operation(summary = "员工退出登录")
    public DailyAimResult<?> logout(HttpServletRequest request, HttpServletResponse response,@RequestBody UserInfoDTO userInfoDTO) {
        log.info("员工ID：{}，退出登录", BaseContext.getCurrentId());
        String token = request.getHeader("Authorization");
        if (ObjectUtils.isEmpty(token)) { // header没有token
            token = request.getParameter("Authorization");
        }
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            // 清除上下文
            new SecurityContextLogoutHandler().logout(request, response, authentication);
            // 清理redis
            redisCache.deleteObject(DailyAuthConstant.TOKEN_PREFIX + BaseContext.getCurrentId());
            // 清理ThreadLocal
            BaseContext.removeCurrentId();
        }
        return DailyAimResult.success();
    }
}
